package com.yanq.liancar.activity;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxtool.view.RxToast;
import com.yanq.liancar.R;
import com.yanq.liancar.activity.base.BaseToolbarActivity;
import com.yanq.liancar.adapter.ShopListAdapter;
import com.yanq.liancar.bean.ShopListBean;
import com.yanq.liancar.url.Config;
import com.yanq.liancar.util.LogUtils;
import com.yanq.liancar.util.ToastUtil;
import com.yanq.liancar.util.Utils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class SmallCSearchActivity extends BaseToolbarActivity {

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_left)
    TextView tvLeft;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.iv_right)
    ImageView ivRight;
    @BindView(R.id.common_toolbar)
    Toolbar commonToolbar;
    @BindView(R.id.action_bar)
    AppBarLayout actionBar;
    @BindView(R.id.et_shopname)
    EditText et_shopname;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.ll_noshop)
    LinearLayout llNoshop;
    @BindView(R.id.text1)
    TextView text1;
    @BindView(R.id.text2)
    TextView text2;
    @BindView(R.id.text3)
    TextView text3;
    private int type;       //0：小C   1：大C
    //声明AMapLocationClient类对象
    private AMapLocationClient mLocationClient = null;
    //声明AMapLocationClientOption对象
    private AMapLocationClientOption mLocationOption = null;
    private double Latitude, Longitude;

    private List<ShopListBean.DataBean> shopListBeanList = new ArrayList<>();
    private ShopListAdapter adapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_smallcsearch);
        Utils.setStatusBar(this, true, false);
        ButterKnife.bind(this);
        mTvTitle.setText("搜索");
        mTvRight.setVisibility(View.VISIBLE);
        mTvRight.setText("搜索");
        mTvRight.setTextColor(getResources().getColor(R.color.main_color));
        type = getIntent().getExtras().getInt("type");
        initRecyclerView();
        mTvRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!TextUtils.isEmpty(et_shopname.getText().toString().trim())) {
                    getLotteryNum();
                } else {
                    Toast.makeText(mContext, "请输入搜索的店铺名称", Toast.LENGTH_SHORT).show();
                }
            }
        });

        getLocation();
    }

    private void initRecyclerView() {
        recyclerview.setNestedScrollingEnabled(false);
        recyclerview.setLayoutManager(new LinearLayoutManager(mContext));
        adapter = new ShopListAdapter(R.layout.item_fuwu, shopListBeanList);
        recyclerview.setAdapter(adapter);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Bundle bundle = new Bundle();
                bundle.putInt("shopId", shopListBeanList.get(position).getId());
                LogUtils.e("shopId", shopListBeanList.get(position).getId() + "");
                RxActivityTool.skipActivity(mContext, ShopDetailsActivity.class, bundle);
            }
        });
    }

    private void getLotteryNum() {
        ToastUtil.showProgressDialog(this);
        OkGo.<String>get(Config.s + "llc/shop/queryShopByNameAndType")
                .tag(this)
                .params("shopName", et_shopname.getText().toString().trim())
                .params("lat", Latitude)
                .params("lon", Longitude)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        LogUtils.e("qeqweqe", response.body());
                        Gson gson = new Gson();
                        ShopListBean baseBean = gson.fromJson(response.body(), ShopListBean.class);
                        if (baseBean.isIsSuccess()) {
                            ToastUtil.dismissProgressDialog();
                            shopListBeanList.clear();
                            shopListBeanList.addAll(baseBean.getData());
                            if (shopListBeanList.size() < 1) {
                                llNoshop.setVisibility(View.VISIBLE);
                            } else {
                                llNoshop.setVisibility(View.GONE);
                                adapter.notifyDataSetChanged();
                            }
                        } else {
                            ToastUtil.dismissProgressDialog();
                            RxToast.error(baseBean.getOutputMessage());
                        }
                    }
                });
    }

    private void getLocation() {
        mLocationClient = new AMapLocationClient(this);
        mLocationOption = new AMapLocationClientOption();
        //        /**
        //         * 设置定位场景，目前支持三种场景（签到、出行、运动，默认无场景）
        //         */
        //        mLocationOption.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.SignIn);
        //        if(null != mLocationClient){
        //            mLocationClient.setLocationOption(mLocationOption);
        //            //设置场景模式后最好调用一次stop，再调用start以保证场景模式生效
        //            mLocationClient.stopLocation();
        //            mLocationClient.startLocation();
        //        }

        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //获取一次定位结果
        mLocationOption.setOnceLocation(true);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //关闭缓存机制
        mLocationOption.setLocationCacheEnable(true);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
        mLocationClient.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                if (aMapLocation != null) {
                    if (aMapLocation.getErrorCode() == 0) {
                        Latitude = aMapLocation.getLatitude();//获取纬度
                        Longitude = aMapLocation.getLongitude();//获取经度
                        LogUtils.e("经纬度====", Latitude + "=======" + Longitude);

                    } else {
                        //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                        Log.e("AmapError", "location Error, ErrCode:"
                                + aMapLocation.getErrorCode() + ", errInfo:"
                                + aMapLocation.getErrorInfo());
                    }
                }
            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mLocationClient) {
            /**
             * 如果AMapLocationClient是在当前Activity实例化的，
             * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
             */
            mLocationClient.onDestroy();
            mLocationClient = null;
            mLocationOption = null;
        }
    }

    @OnClick({R.id.text1, R.id.text2, R.id.text3})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.text1:
                Bundle bundle = new Bundle();
                bundle.putInt("type", 1);
                RxActivityTool.skipActivity(this, DelicateCarWashContentActivity.class,bundle);
                break;
            case R.id.text2:
                RxActivityTool.skipActivity(this, SmallCFuelFillingActivity.class);
                break;
            case R.id.text3:
                RxActivityTool.skipActivity(this, SmallCBuyVIPActivity.class);
                break;
        }
    }
}
